package cn.cloudtogo.common.util;

import cn.cloudtogo.common.Assert;
import cn.cloudtogo.common.model.DatasourceTypes;
import cn.cloudtogo.common.types.ConnectString;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.datasource.DriverManagerDataSource;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Objects;

/**
 * @author yaolianhua789@gmail.com
 **/
public final class JdbcConnectionHelper {

    private JdbcConnectionHelper() {
    }

    public static Connection getConnection(ConnectString connectString) throws SQLException {
        Assert.notNull(connectString, () -> "connectString is null");
        Assert.state(Objects.equals(connectString.getType(), DatasourceTypes.Mysql), () -> "datasource type does not matched mysql");

        String url = String.format("jdbc:mysql://%s:%s", connectString.getEndpoint().getHost(), connectString.getEndpoint().getPort());
        //schema可能不存在，但连接应该有效
        /*if (StringUtils.hasText(connectString.getSchema())) {
            url = String.format("jdbc:mysql://%s:%s/%s", connectString.getServerInfo().getHost(), connectString.getServerInfo().getPort(), connectString.getSchema());
        }*/
        return DriverManager.getConnection(url, connectString.getCredential().getUser(), connectString.getCredential().getPassword());
    }

    public static boolean isValidConnection(ConnectString connectString) {
        try {
            Connection connection = getConnection(connectString);
            return null != connection;
        } catch (SQLException e) {
            return false;
        }
    }

    public static boolean isValidConnection(String url) {
        try {
            Connection connection = DriverManager.getConnection(url);
            return null != connection;
        } catch (SQLException throwables) {
            return false;
        }
    }

    public static JdbcTemplate getJdbcTemplate(ConnectString connectString) {
        Assert.notNull(connectString, () -> "connectString is null");
        Assert.state(Objects.equals(connectString.getType(), DatasourceTypes.Mysql), () -> "datasource type does not matched mysql");

        String host = connectString.getEndpoint().getHost();
        Integer port = connectString.getEndpoint().getPort();
        String schema = connectString.getSchema();
        String username = connectString.getCredential().getUser();
        String password = connectString.getCredential().getPassword();

        String url = String.format("jdbc:mysql://%s:%s", host, port);
        //schema可能不存在，但连接应该有效
        /*if (StringUtils.hasText(schema)) {
            url = String.format("jdbc:mysql://%s:%s/%s", host, port, schema);
        }*/

        DriverManagerDataSource driverManagerDataSource = new DriverManagerDataSource(url, username, password);
        return new JdbcTemplate(driverManagerDataSource);

    }

}
